// Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Xml;
using System.Reflection;
using PfRep.Common.Properties;

namespace PfRep.Common
{
    public static class Config
    {
        public const string PARAM_SQL_SERVER_CONNECTIONSTRING = "SqlServerConnectionString";
        public const string PARAM_SHOW_FOLDER_CONTENTS = "ShowFolderContents";
        public const string PARAM_SHOW_LEGEND = "ShowFolderContents";
        public const string DEFAULT_SQL_CONNECTIONSTRING = "server=Your SQL Server's name";
        public const string URL_HISTORY = "UrlHistory";
        public const string LAST_URL = "LastUrl";
        public const string LAST_USERNAME = "LastUsername";

        // Singleton to cache application settings
        private static Settings appSettings = null;

        /// <summary>
        /// Gets the property with the given name from the specified object
        /// </summary>
        /// <param name="obj">Object</param>
        /// <param name="propertyName">Property name</param>
        /// <returns>Property type object that can be manipulated</returns>
        private static PropertyInfo GetProperty(object obj, string propertyName)
        {
            return obj.GetType().GetProperty(propertyName);
        }

        /// <summary>
        /// Returns the app settings
        /// </summary>
        private static Settings AppSettings
        {
            get
            {
                // Create a new Settings instance if required
                if (appSettings == null)
                    appSettings = new Properties.Settings();

                // Return the app settings
                return appSettings;
            }
        }
        
        /// <summary>
        /// Retrieves a config variable
        /// </summary>
        /// <param name="variable"></param>
        /// <returns></returns>
        public static string GetConfigValue(string variable)
        {
            // Get AppSettings for caching purposes
            Settings cachedAppSettings = AppSettings;
            
            string returnValue = "";

            // Retrieve the actual value from the configuration class
            returnValue = (string)GetProperty(
                cachedAppSettings, variable).GetValue(cachedAppSettings, null);

            /*
            // Get the config value
            string configValue = ConfigurationManager.AppSettings[variable];

            // Return it, or empty string if it's not configured
            if (!string.IsNullOrEmpty(configValue))
                returnValue = configValue;

            Diagnostics.Trace("GetConfigEntry", "Retrieved config entry " + variable +
                ". Its value is '" + returnValue + "'");
            */

            return returnValue;
        }

        /// <summary>
        /// Re-reads the config variables
        /// </summary>
        public static void RefreshConfig()
        {
        }

        /// <summary>
        /// Stores a config variable
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static void SetConfigValue(string key, string value)
        {
            // Get AppSettings for caching purposes
            Settings cachedAppSettings = AppSettings;

            // Retrieve the actual value from the configuration class
            GetProperty(cachedAppSettings, key).SetValue(
                cachedAppSettings, value, null);

            // Save the config
            cachedAppSettings.Save();

            /*
            // Read the config section
            System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            // Check if the config value already exists by reading the section
            KeyValueConfigurationElement configValue = null;
            configValue = config.AppSettings.Settings[key];

            // Update or add the value
            if (configValue == null)
                config.AppSettings.Settings.Add(key, value);
            else
                configValue.Value = value;
            
            // Save the config file
            config.Save();
            */

            Diagnostics.Trace("SetConfigValue", "Set config entry " + key +
                ". Its new value is '" + value + "'");

            /*
            // Refresh the config
            ConfigurationManager.RefreshSection("appSettings");

            Diagnostics.Trace("SetConfigValue", "AppSettings refreshed");
            */
        }

        #region Write helpers
        private static XmlDocument loadConfigDocument()
        {
            XmlDocument doc = null;
            try
            {
                // Retrieve the config path
                string configPath = getConfigFilePath();
                
                doc = new XmlDocument();
                doc.Load(configPath);
                return doc;
            }
            catch (System.IO.FileNotFoundException e)
            {
                throw new Exception("No configuration file found.", e);
            }
        }

        private static string getConfigFilePath()
        {
            return ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath;
        }
        #endregion
    }
}
